package com.springboot_blog.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.regex.Pattern;

/**
 * 密码工具类
 */
public class PasswordUtils {
    private static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    /**
     * 密码强度正则表达式：至少包含数字和字母，长度6-20位
     */
    private static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{6,20}$";
    private static final Pattern pattern = Pattern.compile(PASSWORD_PATTERN);

    /**
     * 加密密码
     */
    public static String encode(String password) {
        return passwordEncoder.encode(password);
    }

    /**
     * 验证密码
     */
    public static boolean matches(String password, String encodedPassword) {
        return passwordEncoder.matches(password, encodedPassword);
    }

    /**
     * 验证密码强度
     */
    public static boolean isValidPassword(String password) {
        return pattern.matcher(password).matches();
    }

    /**
     * 生成随机密码
     */
    public static String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

}
